package com.example.booksdeal.basic;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.booksdeal.BmobDBO.BooksDetail;
import com.example.booksdeal.BmobDBO.Collect;
import com.example.booksdeal.BmobDBO.Comment;
import com.example.booksdeal.BmobDBO.ShopList;
import com.example.booksdeal.BmobDBO.User;
import com.example.booksdeal.R;
import com.example.booksdeal.adapter.MyAdapter;
import com.example.booksdeal.util.DBOpenHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class BooksDetailActivity extends AppCompatActivity {

    private DBOpenHelper dbOpenHelper;
    private SQLiteDatabase db;
    private TextView nickname,bname,price,oprice,hownew,getway,
            type,detail,address,time,commentnum;
    private ImageView image,collectImg;
    private String gid,getImg,comment,username,nicheng,fstime,pushname;
    private Button touch,commentbtn,buy;
    private EditText commentedt;
    private ListView commentlist;
    private LinearLayout layout_back,collect;
    private onClick myOnClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_books_detail);
        dbOpenHelper = new DBOpenHelper(this,"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        db = dbOpenHelper.getWritableDatabase();
        Bundle bundle = this.getIntent().getExtras();
        gid = bundle.getString("id");
        username = bundle.getString("username");
        Log.i("Test", "onCreate: " + gid);
        initview();
    }

    // 初始化页面
    private void initview() {
        nickname = findViewById(R.id.nickname);
        bname = findViewById(R.id.bname);
        price = findViewById(R.id.price);
        oprice = findViewById(R.id.oprice);
        hownew = findViewById(R.id.hownew);
        getway = findViewById(R.id.getway);
        type = findViewById(R.id.type);
        detail = findViewById(R.id.detail);
        address = findViewById(R.id.address);
        image = findViewById(R.id.image);
        time = findViewById(R.id.time);
        touch = findViewById(R.id.lianxi);
        commentbtn = findViewById(R.id.commentbtn);
        buy = findViewById(R.id.buy);
        commentedt = findViewById(R.id.commentedt);
        commentlist = findViewById(R.id.commentlist);
        commentnum = findViewById(R.id.commentnum);
        layout_back = findViewById(R.id.layout_back);
        collect = findViewById(R.id.collect);
        collectImg = findViewById(R.id.collectImg);

        oprice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG ); //中间横线（删除线）
        oprice.getPaint().setAntiAlias(true);// 抗锯齿

        myOnClick = new onClick();
        commentbtn.setOnClickListener(myOnClick);
        touch.setOnClickListener(myOnClick);
        buy.setOnClickListener(myOnClick);
        collect.setOnClickListener(myOnClick);

        BmobQuery<BooksDetail> query = new BmobQuery<>();
        String bql = "select include pushname, * from BooksDetail where objectId = ?";
        query.setSQL(bql);
        query.setPreparedParams(new Object[]{gid});
        query.doSQLQuery(new SQLQueryListener<BooksDetail>(){

            @SuppressLint("SetTextI18n")
            @Override
            public void done(BmobQueryResult<BooksDetail> result, BmobException e) {
                if(e ==null){
                    List<BooksDetail> object = (List<BooksDetail>) result.getResults();
                    if(object!=null && object.size()>0){
                        bname.setText(object.get(0).getBook_name());
                        price.setText("￥" + object.get(0).getBook_price());
                        oprice.setText("￥" + object.get(0).getBook_oprice());
                        hownew.setText(object.get(0).getBook_hownew());
                        getway.setText(object.get(0).getBook_fuc());
                        type.setText(object.get(0).getBook_type());
                        detail.setText(object.get(0).getBook_detail());
                        address.setText(object.get(0).getAddress());
                        getImg = object.get(0).getBook_img();
                        Log.i("Test", "initview: " + getImg);
                        image.setImageBitmap(BitmapFactory.decodeFile(getImg));
                        time.setText(object.get(0).getCreatedAt());
                        nickname.setText(object.get(0).getPushname().getNickname());
                    }
                }
            }
        });

        BmobQuery<Comment> query2 = new BmobQuery<Comment>();
        String bql2 = "select include user, * from Comment where cmt_id = ? order by -createdAt";
        query2.setSQL(bql2);
        query2.setPreparedParams(new Object[]{gid});
//        BooksDetail booksDetail = new BooksDetail();
//        booksDetail.setObjectId(gid);
//        query2.addWhereEqualTo("booksDetail",new BmobPointer(booksDetail));
//        query2.include("user,booksDetail.pushname");
        final ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();
//        query2.findObjects(new FindListener<Comment>() {
//            @Override
//            public void done(List<Comment> list, BmobException e) {
//                if (e == null) {
//                    if (list != null && list.size() > 0) {
//                        layout_back.setVisibility(View.INVISIBLE); // 将layout_back隐藏起来
//                        for (Comment q : list) {
//                            HashMap<String, Object> map = new HashMap<String, Object>();
//                            map.put("nicheng", q.getUser().getNickname());
//                            map.put("comment", q.getComment());
//                            map.put("time", q.getCreatedAt());
//                            listItem.add(map);
//                            SimpleAdapter simpleAdapter = new SimpleAdapter(BooksDetailActivity.this, listItem, R.layout.activity_comment_item,
//                                    new String[]{"nicheng", "comment", "time"}, new int[]{R.id.nicheng, R.id.commenttv, R.id.time});
//                            setListViewHeight(commentlist, simpleAdapter, listItem.size());
//                            commentlist.setAdapter(simpleAdapter);
//                            simpleAdapter.notifyDataSetChanged();
//                        }
//                    }
//                }
//            }
//        });
        query2.doSQLQuery(new SQLQueryListener<Comment>(){

            @Override
            public void done(BmobQueryResult<Comment> result, BmobException e) {
                if (e == null) {
                    List<Comment> object = (List<Comment>) result.getResults();
                    if (object != null && object.size() > 0) {
                        layout_back.setVisibility(View.INVISIBLE); // 将layout_back隐藏起来
                        for (int i = 0; i < object.size(); i++) {
                            HashMap<String, Object> map = new HashMap<String, Object>();
                            map.put("nicheng", object.get(i).getUser().getNickname());
                            map.put("comment", object.get(i).getComment());
                            map.put("time", object.get(i).getCreatedAt());
                            listItem.add(map);
                            Log.i("Test", "listItem: " + listItem + listItem.size());
                            SimpleAdapter simpleAdapter = new SimpleAdapter(BooksDetailActivity.this, listItem, R.layout.activity_comment_item,
                                    new String[]{"nicheng", "comment", "time"}, new int[]{R.id.nicheng, R.id.commenttv, R.id.time});
                            setListViewHeight(commentlist, simpleAdapter, listItem.size());
                            commentlist.setAdapter(simpleAdapter);
                            simpleAdapter.notifyDataSetChanged();
                            commentnum.setText(listItem.size() + "");
                        }
                    }
                }
            }
        });

        BmobQuery<Collect> query3 = new BmobQuery<>();
        String bql3 = "select * from Collect where username = ? and clt_id = ?";
        query3.setSQL(bql3);
        query3.setPreparedParams(new Object[]{username,gid});
        query3.doSQLQuery(new SQLQueryListener<Collect>(){

            @Override
            public void done(BmobQueryResult<Collect> result, BmobException e) {
                if(e ==null){
                    List<Collect> object = (List<Collect>) result.getResults();
                    if(object!=null && object.size()>0){
                        collectImg.setImageResource(R.drawable.shoucanged);
                    }else {
                        collectImg.setImageResource(R.drawable.shoucang);
                    }
                }
            }
        });
//        Cursor cursor = db.query("BooksDetail",null, "id=?",new String[]{gid},null,null,null);
//        while (cursor.moveToNext()) {
//            bname.setText(cursor.getString(cursor.getColumnIndex("book_name")));
//            price.setText("￥" + cursor.getString(cursor.getColumnIndex("book_price")));
//            oprice.setText("￥" + cursor.getString(cursor.getColumnIndex("book_oprice")));
//            hownew.setText(cursor.getString(cursor.getColumnIndex("book_hownew")));
//            getway.setText(cursor.getString(cursor.getColumnIndex("book_fuc")));
//            type.setText(cursor.getString(cursor.getColumnIndex("book_type")));
//            detail.setText(cursor.getString(cursor.getColumnIndex("book_detail")));
//            address.setText(cursor.getString(cursor.getColumnIndex("address")));
//            getImg = cursor.getString(cursor.getColumnIndex("book_img"));
//            Log.i("Test", "initview: " + getImg);
//            image.setImageBitmap(BitmapFactory.decodeFile(getImg));
//            time.setText(cursor.getString(cursor.getColumnIndex("time")));
//            Cursor cursor1 = db.query("UserInfo",null, "username=?",new String[]{cursor.getString(cursor.getColumnIndex("username"))},null,null,null);
//            while (cursor1.moveToNext()) {
//                nickname.setText(cursor1.getString(cursor1.getColumnIndex("nickname")));
//            }
//            Cursor cursor2 = db.query("Comment",null, "cmt_id=?",new String[]{gid},null,null,"cmt_time desc","5");
//            final ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();
//            if (cursor2 != null && cursor2.getCount() > 0) {
//                layout_back.setVisibility(View.INVISIBLE); // 将layout_back隐藏起来
//                while (cursor2.moveToNext()) {
//                    nicheng = cursor2.getString(cursor2.getColumnIndex("username"));
//                    comment = cursor2.getString(cursor2.getColumnIndex("comment"));
//                    fstime = cursor2.getString(cursor2.getColumnIndex("cmt_time"));
//                    HashMap<String,Object> map = new HashMap<String,Object>();
//                    map.put("nicheng",nicheng);
//                    map.put("comment",comment);
//                    map.put("time",fstime);
//                    listItem.add(map);
//                    Log.i("Test", "listItem: " + listItem + listItem.size());
//                    SimpleAdapter simpleAdapter = new SimpleAdapter(this,listItem,R.layout.activity_comment_item,
//                            new String[]{"nicheng","comment","time"},new int[]{R.id.nicheng,R.id.commenttv,R.id.time});
//                    setListViewHeight(commentlist, simpleAdapter, listItem.size());
//                    commentlist.setAdapter(simpleAdapter);
//                }
//            }
//            Cursor cursor3 = db.query("Collect",null, "username=? and clt_id=?",new String[]{username,gid},null,null,null);
//            if (cursor3 != null && cursor3.getCount() > 0) {
//                collectImg.setImageResource(R.drawable.shoucanged);
//            }
//            else {
//                collectImg.setImageResource(R.drawable.shoucang);
//            }
//            commentnum.setText(listItem.size() + "");
//        }
    }

    public class onClick implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.commentbtn:
                    Commented();
                    initview();
                    break;
                case R.id.lianxi:
                    Touch();
                    break;
                case R.id.buy:
                    Buy();
                    break;
                case R.id.collect:
                    Collect();
                    break;
            }
        }
    }

    // 发送评论
    private void Commented() {
        if (commentedt.getText().toString().trim().equals("")) {
            Toast toast = Toast.makeText(this, "评论不能为空", Toast.LENGTH_SHORT); //生成Toast对象
            toast.show();
        } else {
            final Comment comment = new Comment();
            BooksDetail booksDetail = new BooksDetail();
            booksDetail.setObjectId(gid);
            comment.setCmt_id(gid);
            comment.setComment(commentedt.getText().toString());
            comment.setUsername(username);
            comment.setBook(booksDetail);
            comment.setUser(User.getCurrentUser(User.class));
            comment.save(new SaveListener<String>() {
                @Override
                public void done(String objectid, BmobException e) {
                    if(e==null)
                    {
                        Toast.makeText(BooksDetailActivity.this, "评论成功！", Toast.LENGTH_SHORT).show();
                    }else
                    {
                        Log.e("评论失败", "原因: ",e );
                    }
                }
            });
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd   HH:mm:ss");
//            Date curDate = new Date(System.currentTimeMillis());
//            ContentValues values = new ContentValues();
//            values.put("cmt_id",gid);
//            values.put("comment", commentedt.getText().toString());
//            values.put("cmt_time", formatter.format(curDate));
//            values.put("username", username);
//            db.insert("Comment", null, values);
            commentedt.setText("");
        }
    }

    // 联系卖家
    private void Touch() {
        Intent intent = new Intent(BooksDetailActivity.this,ChatActivity.class);
        intent.putExtra("gid",gid);
        startActivity(intent);
    }

    // 购买
    private void Buy() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(BooksDetailActivity.this);
        normalDialog.setTitle("是否确定购买?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ShopList shopList = new ShopList();
                        BooksDetail booksDetail = new BooksDetail();
                        booksDetail.setObjectId(gid);
                        shopList.setSlt_id(gid);
                        shopList.setUsername(username);
                        shopList.setBook(booksDetail);
                        shopList.setUser(User.getCurrentUser(User.class));
                        shopList.save(new SaveListener<String>() {
                            @Override
                            public void done(String objectid, BmobException e) {
                                if(e==null)
                                {
                                    Toast.makeText(BooksDetailActivity.this, "购买成功！", Toast.LENGTH_SHORT).show();
                                }else
                                {
                                    Log.e("购买失败", "原因: ",e );
                                }
                            }
                        });
//                        ContentValues values = new ContentValues();
//                        values.put("slt_id",gid);
//                        values.put("username",username);
//                        db.insert("ShopList",null,values);
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }

    // 收藏
    private void Collect() {
        BmobQuery<Collect> query = new BmobQuery<Collect>();
        String bql = "select * from Collect where username = ? and clt_id = ?";
        query.setSQL(bql);
        query.setPreparedParams(new Object[]{username,gid});
  //      query.addWhereEqualTo("user",User.getCurrentUser(User.class));
//        query.findObjects(new FindListener<Collect>() {
//            @Override
//            public void done(List<Collect> list, BmobException e) {
//                if(e == null){
//                    if(list!=null && list.size()>0){
//                        //Collect为表名
//                        Collect collect1 = new Collect();
//                        collect1.setObjectId(list.get(0).getObjectId());
//                        collect1.delete(new UpdateListener() {
//
//                            @Override
//                            public void done(BmobException e) {
//                                if(e==null){
//                                    Toast.makeText(BooksDetailActivity.this,"取消收藏",Toast.LENGTH_LONG).show();
//                                    collectImg.setImageResource(R.drawable.shoucang);
//                                }
//                            }
//                        });
//                    }else {
//                        Collect collect2 = new Collect();
//                        BooksDetail booksDetail = new BooksDetail();
//                        booksDetail.setObjectId(gid);
//                        collect2.setClt_id(gid);
//                        collect2.setUsername(username);
//                        collect2.setUser(User.getCurrentUser(User.class));
//                        collect2.setBook(booksDetail);
//                        collect2.save(new SaveListener<String>() {
//                            @Override
//                            public void done(String s, BmobException e) {
//                                Toast.makeText(BooksDetailActivity.this,"收藏成功",Toast.LENGTH_LONG).show();
//                                collectImg.setImageResource(R.drawable.shoucanged);
//                            }
//                        });
//                    }
//                }
//            }
//        });
        query.doSQLQuery(new SQLQueryListener<Collect>(){

            @Override
            public void done(BmobQueryResult<Collect> result, BmobException e) {
                if(e == null){
                    List<Collect> object = (List<Collect>) result.getResults();
                    if(object!=null && object.size()>0){
                        //Collect为表名
                        Collect collect1 = new Collect();
                        collect1.setObjectId(object.get(0).getObjectId());
                        collect1.delete(new UpdateListener() {

                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    Toast.makeText(BooksDetailActivity.this,"取消收藏",Toast.LENGTH_LONG).show();
                                    collectImg.setImageResource(R.drawable.shoucang);
                                }
                            }
                        });
                    }else {
                        Collect collect2 = new Collect();
                        BooksDetail booksDetail = new BooksDetail();
                        booksDetail.setObjectId(gid);
                        collect2.setClt_id(gid);
                        collect2.setUsername(username);
                        collect2.setUser(User.getCurrentUser(User.class));
                        collect2.setBook(booksDetail);
                        collect2.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                Toast.makeText(BooksDetailActivity.this,"收藏成功",Toast.LENGTH_LONG).show();
                                collectImg.setImageResource(R.drawable.shoucanged);
                            }
                        });
                    }
                }
            }
        });

//        Cursor cursor = db.query("Collect",null, "username=? and clt_id=?",new String[]{username,gid},null,null,null);
//        if (cursor != null && cursor.getCount() > 0) {
//            db.delete("Collect","clt_id=?",new String[]{gid});
//            Toast.makeText(BooksDetailActivity.this,"取消关注",Toast.LENGTH_LONG).show();
//            collectImg.setImageResource(R.drawable.shoucang);
//            }
//        else {
//                ContentValues values = new ContentValues();
//                values.put("clt_id",gid);
//                values.put("username",username);
//                db.insert("Collect",null,values);
//                Toast.makeText(BooksDetailActivity.this,"收藏成功",Toast.LENGTH_LONG).show();
//                collectImg.setImageResource(R.drawable.shoucanged);
//            }
    }


    // 设置ListView能显示个数的高度
    private void setListViewHeight(ListView listView, SimpleAdapter adapter, int count) {
        int totalHeight = 0;
        for (int i = 0; i < count; i++) {
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * count) + 140;
        listView.setLayoutParams(params);
    }
}
